package uk.ac.cam.cl.android.jwdb;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

public class LiftListener implements SensorEventListener {
	private SensorManager sensorManager;
	private Sensor accelerometer;
	private static boolean hasHadLift = false;
	private static boolean hasHadDrop = false;
	private static Action liftListener = null;
	private static Action dropListener = null;
	
	public LiftListener(Context context) {
		sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
	    accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
	    sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// ...
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		if (event.sensor == accelerometer) {
			float x = event.values[0];
			float y = event.values[1];
			float z = event.values[2];
			
			if (9.8 - z > 4.0 && x < 2.5 && y < 2.5) {
				Log.d("Sensor", "Lifting");
				hasHadLift = true;
				if (liftListener != null) liftListener.done();
			}
			if (z - 9.8 > 4.0 && x < 2.5 && y < 2.5) {
				Log.d("Sensor", "Dropping");
				hasHadDrop = true;
				if (dropListener != null) dropListener.done();
			}
		}
	}
	
	public static boolean hasHadLift() {
		if (hasHadLift) {
			hasHadLift = false;
			return hasHadLift;
		}
		else return false;
	}
	
	public static boolean hasHadDrop() {
		if (hasHadDrop) {
			hasHadDrop = false;
			return hasHadDrop;
		}
		else return false;
	}
	
	public static void registerLiftListener(Action theListener) {
		liftListener = theListener;
	}
	
	public static void registerDropListener(Action theListener) {
		dropListener = theListener;
	}

}
